package com.example.postman.postReques;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.postman.postReques.util.HttpUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

public class TestPostRequest {
    public static void main(String[] args) {
        String baseUrl = "https://apis.tianapi.com/esports/index?key=";
        String uniqueKey = "3a9946532ebd36a1b6847878f6748db5";
        String url = baseUrl + uniqueKey;//访问路径
        Random random = new Random();
        Map<String, Object> params = new HashMap<>();
        params.put("authCode", "1423009170000001");
        params.put("resource", "api.hl.order.pay.unified");
        params.put("requestTime", "20230129105758");
        params.put("versionNo", "1");
        params.put("goodsInfo", "{\"receiptid\":\"323323\",\"costprice\":200.00,\"goodsdetail\":[{\"goodsid\":\"123123123\",\"goodsname\":\"小石头\",\"thirdgoodsid\":\"23323453\",\"quantity\":1,\"price\":5.00}]}");
        params.putAll(params);
        //排序集合
        params = PaySortUtil.sortByKey(params);
        //遍历输出拼接字符串
        Set<String> keys = params.keySet();
        String str = "";
        for (String key : keys) {
            str += key + "=" + params.get(key) + "&";
        }
        str = str.toLowerCase() + "U7iIPg2x1k";
        //md5加密字符串
        String md5sr = DigestUtils.md5DigestAsHex(str.getBytes());
        params.put("sign", md5sr);
        Map<String, Object> map3 = new HashMap<>();//存放结果
        //将需要比较删除的两个集合添加
        map3.putAll(params);
        //for - each遍历比较且删除
        for (String a : params.keySet()) {
            if (params.containsKey(a) || params.containsValue(params.get(a))) {
                map3.remove(a);
            }
        }
        map3.put("versionNo", "1");
        map3.put("params", params);
        // System.out.println("map3 = "+ map3);
        String map3Str = (String) params.get("goodsInfo");
        JSONObject jsonObject = JSONObject.parseObject(map3Str);
        // System.out.println(jsonObject.toString());

       //  String data = HttpUtil.post(url, jsonObject.toString());
        CloseableHttpResponse response = HttpUtil.postResponse(url, jsonObject.toString());
        Map<String, Object> map = handleData(response);
        // 处理返回的数据
        Object result = map.get("result");
        String replace = JSONObject.toJSONString(result);

        ArticleTitleDTO dto = JSONArray.parseObject(replace, ArticleTitleDTO.class);
        dto.setList((List<ArticleTitle>) map.get("newslist"));
        System.out.println(dto.getList().size());
    }

    /**
     * 处理返回的response
     *
     * @param response response
     * @return Map
     */
    private static Map<String, Object> handleData(CloseableHttpResponse response) {
        int code = response.getStatusLine().getStatusCode();
        Map<String, Object> map;
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> mapResult;
        try {
            HttpEntity entity = response.getEntity();
            if (!StringUtils.isEmpty(entity)) {
                map = JSONObject.parseObject(EntityUtils.toString(entity));
                result.put("code", code);
                if (code != 200) {
                    response.setStatusCode(code);
                }else {
                    result.put("code", code);
                    result.put("result", map.get("result"));
                    result.put("msg", map.get("msg"));
                    mapResult = JSONObject.parseObject(JSONObject.toJSONString(map.get("result")));
                    List<ArticleTitle> newslist = (List<ArticleTitle>) mapResult.get("newslist");
                    result.put("newslist", newslist);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送post 请求
     *
     * @param url url
     * @param param param
     * @return String
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.err.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

}

class PaySortUtil {
    public static Map<String, Object> sortByKey(Map<String, Object> map) {
        //创建一个带有比较器的TreeMap
        Map<String, Object> treeMap = new TreeMap<>(String::compareTo);
        //将你的map传入treeMap
        treeMap.putAll(map);
        return treeMap;
    }
}

